﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Net;
using log4net;
using log4net.Config;

namespace ConsoleApplicationForTesting
{
    class Program
    {
        protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
        /// <summary>
        /// 1.8.2013:idee, gebe alle NetzwerkComputer aus
        /// 
        /// using log4net: http://sadi02.wordpress.com/2008/06/29/log4net-tutorial-in-c-net-how-can-i-show-log-in-a-file/
        ///  - used loglevel: error and debug
        ///  - logfile 'NetworkScanner.log' in same folder like the application (see app.config)
        /// </summary>
        /// <param name="args">
        /// Array:
        /// 1. Parameter: activator for logging, if true: logging is on
        /// 2. Parameter: not used!
        /// </param>
        static void Main(string[] args)
        {
            var myBr = new NetworkBrowser();
            //angaf: see http://msdn.microsoft.com/en-us/library/windows/desktop/aa370623(v=vs.85).aspx
            //int SV_TYPE_NT = 1000 :: take any workstation or server.
            //int SV_TYPE_WORKSTATION = 1; All workstations.
            //int SV_TYPE_SERVER = 2; All computers that run the Server service.
            // SV_TYPE_ALL = 0xFFFFFFFF; 4294967295:: list of all servers
            // SV_TYPE_SERVER_NT = 8000; :: Any server that is not a domain controller.
            // SV_TYPE_DOMAIN_CTRL = 8 :: A server that is primary domain controller.
            // SV_TYPE_DOMAIN_BAKCTRL = 10 :: any server that is a backup domain controller.
            // 
            
            System.Console.WriteLine("starte...");
            System.Console.WriteLine("-------------------------------------------------------");
            
            //check first parameter: log activator:           
            if (args != null && args.Length > 0 && args[0] == "true")
            {
                //enable Logging:
                log4net.Config.XmlConfigurator.Configure();
                log.Debug("Logging is activated");
            }            
            log.Debug("starting ------------------------------------- timestamp:" + DateTime.Now);

            //get the domain:
            var domain = myBr.GetDomainNameAndHostname();
            System.Console.WriteLine("1. untersuche den lokalen Rechner:");
            System.Console.WriteLine(" - hostname.domain=" + domain);

            //get the ip for the local computer:            
            IPAddress localIP = myBr.getIPAddress(myBr.getLocalComputername());
            if (localIP != null)
            {
                System.Console.WriteLine(" - lokale IP:" + localIP.ToString());
                log.Debug(" - lokale IP:" + localIP.ToString());
            }
            else
            {
                System.Console.WriteLine(" - Attention: lokale IP not set! stopping here!");
                log.Debug(" - Attention: lokale IP not set! stopping here!");
                return;
            }            
            System.Console.WriteLine("-------------------------------------------------------");
            
            System.Console.WriteLine("2. getting PCNames from ListNetworkComputersAsString():");
            log.Debug("2. getting PCNames from ListNetworkComputersAsString():");
            var myList = myBr.ListNetworkComputersAsString();
            foreach (string onePCName in myList)
            {
                System.Console.WriteLine(onePCName + ", IP:" +  myBr.getIPAddress(onePCName));
                
                List<String> myUserList =myBr.getAllUsers(onePCName);
                if (myUserList.Count > 0)
                {
                    System.Console.WriteLine("  found Users:");

                    foreach (string oneUser in myUserList)
                    {
                        System.Console.WriteLine("   " + oneUser);
                        log.Debug(oneUser);
                    }
                    System.Console.WriteLine("  ---");
                }

                List<String> myShareList = myBr.getShares(onePCName);
                if (myShareList.Count > 0)
                {
                    System.Console.WriteLine("  found Shares:");
                    foreach (string oneShare in myShareList)
                    {
                        System.Console.WriteLine("   " + oneShare);
                        log.Debug(oneShare);
                    }
                    System.Console.WriteLine("  ---");
                }
            }
            System.Console.WriteLine("-------------------------------------------------------");

            System.Console.WriteLine("...Ende!");
            log.Debug("end-------------------------------------------- timestamp:" + DateTime.Now);
        }

        /// <summary>
        /// modifying an xml file
        /// </summary>
        /// <param name="args"></param>
        static void disabled_Main(string[] args)
        {
            
            /*
         * <XMLModify FileName="D:\my_rechtool\kuemmel\make_backups\SimplyBackup.exe.log4net.xml" 
         * XmlTag="configuration/log4net/logger" 
         * SearchAttributeTag="level" 
         * SearchAttributeValue="ALL"
         * ModifiedValue="INFO" 
         * AttributeChange="true" 
         * ModifiedAttribute="value" 
         */  
            string _fileName="D:\\my_rechtool\\kuemmel\\make_backups\\SimplyBackup.exe.log4net.xml";
            string _xmlTag="//configuration/log4net/logger/level";//XPath to the Tag
            string _modifiedAttribute="value"; //attribute for modifying
            string _modifiedValue="INFO"; //new value

            XmlDocument doc = new XmlDocument();
            try
            {                
                doc.Load(_fileName);
                XmlNode node = null;
                node = doc.SelectSingleNode(_xmlTag);
                if (node != null)
                {
                    // see if the attribute exists. if it doesn't, create it.
                    if (node.Attributes[_modifiedAttribute] == null)
                    {
                        node.Attributes.Append(doc.CreateAttribute(_modifiedAttribute));
                    }

                    // assign the attribute to the modified value
                    node.Attributes[_modifiedAttribute].Value = _modifiedValue;

                    // save the xml content back to the file
                    doc.Save(_fileName);

                    // successful task, return
                    //return true;
                }

                // the task failed, return false if the node doesn't exist                
                //Log.LogError("Couldn't find Xml Node - {0} in file {1}", _xmlTag,_fileName);
                //return false;
                System.Console.WriteLine("Couldn't find Xml Node - {0} in file {1}", _xmlTag, _fileName);

            }
            catch (Exception ex)
            {
                //Log.LogError(ex.Message);
                System.Console.WriteLine(ex.Message);
            }
            
            // the task failed.
            //return false;            
        }
        
    }
}
